package com.orange.book.bookServices;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.orange.book.hashDB.HashDB;
import com.orange.bookVO.BookVO;

public class BookService {
	private static final Logger LOG = LoggerFactory.getLogger(BookService.class);

	@POST
	@Path("/getbook/{name}")
	@Produces({ "application/xml", "application/json" })
	@Consumes({ "application/xml", "application/json", "application/x-www-form-urlencoded" })
	public Response getBucket(@PathParam("name") String name) {
		LOG.info("name : " + name);
		BookVO bookVO = null;
		try {
			bookVO = HashDB.getBook(URLDecoder.decode(name, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (bookVO == null) {
			return Response.status(Response.Status.BAD_REQUEST).build();
		} else {
			return Response.ok(bookVO).build();
		}
	}

	@POST
	@Path("/addbook/{name}/{author}")
	@Produces({ "application/xml", "application/json" })
	@Consumes({ "application/xml", "application/json", "application/x-www-form-urlencoded" })
	public Response addBook(@PathParam("name") String bookName, @PathParam("author") String author) {
		LOG.info("inside addBook");
		BookVO bookVO = new BookVO();
		bookVO.setBookName(bookName);
		bookVO.setAuthor(author);
		HashDB.insertBook(bookVO);
		if (HashDB.getBook(bookName) == null) {
			return Response.status(Response.Status.BAD_REQUEST).build();
		} else {
			return Response.ok(bookVO).build();
		}
	}
}
